package io.lkt.modules.sys.controller;

import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import io.lkt.common.util.Query;
import io.lkt.common.utils.DateUtil;
import io.lkt.common.utils.PageUtils;
import io.lkt.common.utils.R;
import io.lkt.common.utils.ToolUtil;
import io.lkt.common.validator.ValidatorUtils;
import io.lkt.modules.job.utils.ExcelUtil;
import io.lkt.modules.sys.dao.SysUserGzhDao;
import io.lkt.modules.sys.entity.*;
import io.lkt.modules.sys.service.*;
import io.lkt.modules.sys.shiro.WeixinService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import io.lkt.modules.sys.entity.BUserInfoEntity;
import io.lkt.modules.sys.entity.BUserWithdrawLogEntity;
import io.lkt.modules.sys.service.BUserInfoService;
import io.lkt.modules.sys.service.BUserWithdrawLogService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 提现申请记录
 *
 * @author xss
 * @email dustwas@163.com
 * @date 2019-04-29 16:09:12
 */
@RestController
@RequestMapping("/sys/buserwithdrawlog")
public class BUserWithdrawLogController  extends AbstractController{
    protected Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private BUserWithdrawLogService bUserWithdrawLogService;

    @Autowired
    private BUserInfoService bUserInfoService;

    private WxPayService wxPayService;

    @Autowired
    private SysUserGzhDao sysUserGzhDao;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    public BUserWithdrawLogController(WxPayService wxPayService) {
        this.wxPayService=wxPayService;
    }

    //public BUserWithdrawLogController(){ }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:buserwithdrawlog:list")
    public R list(@RequestParam Map<String, Object> params){
        SysUserEntity curUser= getUser();
        Long userId = curUser.getUserId();
        params.put("curUserId",userId);
        // 获取系统用户负责的公众号
        List<String> sysUserGzhList = sysUserService.getUserGzhList(userId);
        params.put("sysUserGzhList", sysUserGzhList);

        Query query = new Query(params);
        List<BUserWithdrawLogEntity> list=bUserWithdrawLogService.queryList(query);
        Integer total=bUserWithdrawLogService.queryTotal(query);
        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());

        return R.ok().put("page", page);
    }

    @RequestMapping("/withdrawalCount")
    public R withdrawalCount() {
        Map<String, Object> map = new HashMap<>();
        SysUserEntity curUser= getUser();
        Long userId = curUser.getUserId();
        map.put("curUserId",userId);
        map.put("processStatus", "0");// 待处理
        // 获取系统用户负责的公众号
        List<String> sysUserGzhList = sysUserService.getUserGzhList(userId);
        map.put("sysUserGzhList", sysUserGzhList);

        Integer total=bUserWithdrawLogService.queryTotal(map);
        String latestDetail = "";
        if (total.intValue() > 0) {
            BUserWithdrawLogEntity withdrawal = bUserWithdrawLogService.getLatestWithdrawal(map);
            String latestTime = new SimpleDateFormat("HH:mm:ss").format(withdrawal.getCreateTime());
            latestDetail = latestTime + "  " + withdrawal.getUserName() + "  " + withdrawal.getAmount() + "元";
        }

        return R.ok().put("latestCount", total).put("latestDetail", latestDetail);
    }

    /**
     * 导出表格
     * @param
     * @return
     */
    @RequestMapping("/derivedForm")
    @RequiresPermissions("sys:buserwithdrawlog:list")
    public void derivedForm(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> params=new HashMap<String, Object>();
        SysUserEntity curUser= getUser();
        params.put("curUserId",curUser.getUserId());
        //Query query = new Query(params);
        List<BUserWithdrawLogEntity> list=bUserWithdrawLogService.queryList(params);
        //excel标题
        String[] title = {"id","用户id","用户昵称","提现金额","申请时间","账号名","银行名称","支行名称","银行账号","电话","公众号","状态"};

        //excel文件名
        String fileName = "提现申请明细表.xls";


        //sheet名
        String sheetName = "提现申请明细表";

        String processStatus = null ;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String[][] content=new String[list.size()][title.length];
        for (int i = 0; i < list.size(); i++) {
            content[i][0] = list.get(i).getId().toString();
            content[i][1] = list.get(i).getUserId().toString();
            content[i][2] = list.get(i).getUserName();
            content[i][3] = list.get(i).getAmount().toString();
            content[i][4] = sdf.format(list.get(i).getCreateTime());
            content[i][5] = list.get(i).getFullName();
            content[i][6] = list.get(i).getBankName();
            content[i][7] = list.get(i).getSubBranch();
            content[i][8] = list.get(i).getBankAccount();
            content[i][9] = list.get(i).getPhone();
            content[i][10] = list.get(i).getGzhName();

            if (list.get(i).getProcessStatus() == 1){
                processStatus ="已打款";
            }else if (list.get(i).getProcessStatus() == 2){
                processStatus="已拒绝";
            }else {
                processStatus="未处理";
            }
            content[i][11] = processStatus;
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            ExcelUtil.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:buserwithdrawlog:info")
    public R info(@PathVariable("id") Integer id){
        BUserWithdrawLogEntity bUserWithdrawLog = bUserWithdrawLogService.getById(id);

        return R.ok().put("bUserWithdrawLog", bUserWithdrawLog);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:buserwithdrawlog:save")
    public R save(@RequestBody BUserWithdrawLogEntity bUserWithdrawLog){
        bUserWithdrawLogService.save(bUserWithdrawLog);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:buserwithdrawlog:update")
    public R update(@RequestBody BUserWithdrawLogEntity bUserWithdrawLog){
        ValidatorUtils.validateEntity(bUserWithdrawLog);
        bUserWithdrawLogService.updateById(bUserWithdrawLog);
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:buserwithdrawlog:delete")
    public R delete(@RequestBody Integer[] ids){
        bUserWithdrawLogService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }
    @RequestMapping("/remit")
    public R remit(Integer userId,Double amount,Integer id){

        System.out.println(userId+">"+amount+">"+id);

        BUserInfoEntity bUserInfo=bUserInfoService.getById(userId);
        /*EntPayRequest request = new EntPayRequest();
        request.setPartnerTradeNo(userId.toString());
        request.setCheckName("NO_CHECK");
        request.setAmount(BaseWxPayRequest.yuanToFen(String.valueOf(amount)));
        request.setDescription("智客推提现付款");

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        request.setSpbillCreateIp(ToolUtil.getIpAddress(attributes.getRequest()));

        String openId = bUserInfo.getOpenId();
        request.setOpenid(openId);*/
        //entPay(userId,request);  //屏蔽于20200314，发现不通，暂时不知道之前逻辑

        //修改为已打款状态
        BUserWithdrawLogEntity bUserWithdrawLog=new BUserWithdrawLogEntity();
        bUserWithdrawLog.setId(id);
        bUserWithdrawLog.setProcessStatus(1);
        bUserWithdrawLog.setModifyTime(new Date());
        bUserWithdrawLogService.updateById(bUserWithdrawLog);

        if (bUserInfo != null && bUserInfo.getOpenId()!=null && bUserInfo.getConcernStatus().equals(1)){

            SysGzhEntity sysGzh= sysUserGzhDao.getGzhByCode(bUserInfo.getGzhCode());

            bUserWithdrawLog=bUserWithdrawLogService.getById(id);

            // 发送模板消息接口
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    // 接收者openid
                    .toUser(bUserInfo.getOpenId())
                    // 模板id
                    .templateId(sysGzh.getWithdrawTempId())
                    .build();
            String firstMsg =sysGzh.getGzhName() +"您申请的提现金额已到帐。\n\n";
            String remarkMsg = "感谢你的使用。\n\n成为代理，获得更高收益，回复【客服】咨询开通。\n\n";

            // 添加模板数据
            templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                    .addData(new WxMpTemplateData("keyword1", "银行卡转帐", "#A9A9A9"))
                    .addData(new WxMpTemplateData("keyword2",  bUserWithdrawLog.getAmount().toString(), "#A9A9A9"))
                    .addData(new WxMpTemplateData("keyword3", DateUtil.getFormatDate("",bUserWithdrawLog.getCreateTime()) , "#A9A9A9"))
                    .addData(new WxMpTemplateData("remark", remarkMsg, "#0000FF"));
            String msgId = null;
            try {
                WxMpServiceImpl wxMpService= WeixinService.getWeixinService(sysGzh);
                // 发送模板消息
                msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            } catch (WxErrorException e) {
                //e.printStackTrace();
            }
        }

        return R.ok();
    }

    public void entPay(Integer userWithdrawId, EntPayRequest request) {
        log.info("[enter entPay] = " + userWithdrawId);
        EntPayResult entPayResult = null;
        try {
            System.out.println(request.getMchId());
            entPayResult = wxPayService.getEntPayService().entPay(request);

        } catch (WxPayException e) {
            System.out.println(entPayResult.getMchId());
            e.printStackTrace();
        }

        log.info("[EntPayResult] = " + JSON.toJSONString(entPayResult));
        log.info("[exit entPay] = " + userWithdrawId);

    }

    @RequestMapping("/getWithdrawByUserId")
    public R getWithdrawByUserId(@RequestParam Map<String, Object> params) {
        if (params.get("userId") == null) {
            return R.error("用户不存在");
        }

        Query query = new Query(params);
        List<BUserWithdrawLogEntity> list = bUserWithdrawLogService.getWithdrawByUserId(query);
        int total = bUserWithdrawLogService.getWithdrawByUserIdTotal(query);

        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }

}
